import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {RoleService} from './role.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PermissionService} from '../../../service/permission.service';
import {HomeService} from '../../home/home.service';


@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss']
})
export class RoleComponent implements OnInit {
  modalForm!: FormGroup; // 模态框表单
  menuForm: any = {}; // 权限框表单
  oldChecked: any[] = []; // 旧的权限列表
  modalLoading = false; // 模态框新建 or 保存 加载中状态
  roleModal = false; // 角色模态框显示 or 隐藏
  menuModal = false; // 权限模态框显示 or 隐藏
  menuModule = ''; // 权限模块
  checked = false; // 是否全选
  // 列表查询条件
  queryForm: any = {
    // 角色名称
    name: '',
    // 每页数量
    pageSize: 20,
    // 当前页
    page: 1
  };
  tableLoading: any = false; // 表格是否加载中
  listOfData?: any; // 列表数据源
  searchHint = false; // 当前是否在搜索
  searcName = ''; // 当前搜索name
  roleTreeOptions: any[] = []; // 权限树待选数组
  moduleList: any;
  module: any;

  constructor(
    private message: NzMessageService,
    private roleService: RoleService,
    private fb: FormBuilder,
    public permission: PermissionService,
    public homeService: HomeService,
  ) {
  }

  ngOnInit(): void {
    this.modalForm = this.fb.group({
      id: [null],
      // 角色名称
      name: [null, [Validators.required]],
      // 权限字符
      keyword: [null],
      // 显示顺序
      sort: [null],
      // 状态
      rStats: ['0'],
      // 备注
      rRemarks: [null],
    });
    this.list();
    this.menuList();
  }

  /**
   * 刷新列表
   */
  refresh() {
    this.listOfData = [];
    this.list();
  }

  /**
   * 查询
   */
  query(): void {
    if (this.queryForm.name === '') {
      return;
    }
    this.searchHint = true;
    this.list();
  }

  /**
   * 搜索返回原列表
   */
  backList() {
    this.queryForm.name = '';
    this.queryForm.page = 1;
    this.searchHint = false;
    this.checked = false;
    this.list();
  }

  /**
   * item单选
   * @param id
   * @param checked
   */
  onItemChecked(id: number, checked: boolean): void {
    const index = this.listOfData.records.findIndex((item: { id: number; }) => item.id === id);
    this.listOfData.records[index].Checked = checked;
    this.updataCheckAll();
  }

  /**
   * 全选
   * @param value
   */
  onAllChecked(value: boolean): void {
    this.listOfData.records.forEach((item: { Checked: boolean; }) => item.Checked = value);
  }

  /**
   * 判断item是否全部选择
   */
  updataCheckAll() {
    const index = this.listOfData.records.findIndex((item: { Checked: boolean; }) => item.Checked == false);

    if (index != -1) {
      this.checked = false;
    } else {
      this.checked = true;
    }
  }

  /**
   * 页码改变
   * @param index
   */
  onPageIndexChange(index: number) {
    console.log(index);
    this.queryForm.page = index;
    this.checked = false;
    this.list();
  }

  /**
   * 每页条数改变的回调
   * @param index
   */
  onPageSizeChange(index: number) {
    console.log(index);
    this.queryForm.pageSize = index;
    this.list();
  }

  /**
   * 删除角色
   * @param id
   */
  confirm(id: any) {
  }

  /**
   * 打开角色权限 模态框初始化
   * @param id
   */
  showMenuModal(id: any = null): void {
    this.menuModal = true;
    this.menuModule = 'A';
    this.menuForm.id = id;
    this.module = this.moduleList[0].id;
    // this.menuList();
    if (id != null) {
      this.queryPermission(id);
    }

  }

  /**
   * 打开角色信息模态框 初始化
   * @param id
   */
  showRoleModal(id: any = null): void {
    this.roleModal = true;
    if (id != null) {
      this.details(id);
    }
  }

  /**
   * 模态框关闭触发
   */
  handleCancel(): void {
    this.roleModal = false;
    this.menuModal = false;
    this.modalForm.reset();
    this.modalForm.get('rStats')!.setValue('0');
  }

  /**
   * 新增 or 编辑 模态框提交
   */
  submitForm(): void {
    for (const i in this.modalForm.controls) {
      if (this.modalForm.controls.hasOwnProperty(i)) {
        this.modalForm.controls[i].markAsDirty();
        this.modalForm.controls[i].updateValueAndValidity();
      }
    }
    if (this.modalForm.status !== 'VALID') {
      return;
    }
    if (this.modalForm.value.id) {
      this.roleService.update(this.modalForm.value).subscribe((res: any) => {
        if (res.code !== 0) {
          this.createMessage('error', res.message);
          return;
        }
        this.createMessage('success', '角色修改成功');
        this.handleCancel();
        this.list();
      }, err => {
      });
    } else {
      this.roleService.add(this.modalForm.value).subscribe((res: any) => {
        if (res.code !== 0) {
          this.createMessage('error', res.message);
          return;
        }
        this.createMessage('success', '角色添加成功');
        this.handleCancel();
        this.list();
      }, err => {
      });
    }
  }

  toEdit(id: any = 0) {
  }

  /**
   * 查询角色列表
   */
  list() {
    if (this.tableLoading) {
      return;
    }
    this.tableLoading = true;
    this.roleService.list(this.queryForm).subscribe((res: any) => {
      this.listOfData = res.data;
      for (let index = 0; index < this.listOfData.records.length; index++) {
        const element = this.listOfData.records[index];
        element.Checked = false;
      }
      this.searcName = this.queryForm.name;
      this.tableLoading = false;
    }, err => {
      this.tableLoading = false;
    });
  }

  /**
   * 权限列表
   */
  menuList() {
    this.homeService.menuList().subscribe(res => {
      if (res.code === 0) {
        this.moduleList = res.data.sys;
        // @ts-ignore
        this.module = this.moduleList[0].id;
        this.moduleList.forEach((m: any) => {
          this.roleService.menuList({sysId: m.id}).subscribe((menu: any) => {
            m.roleTreeOptions = JSON.parse(JSON.stringify(menu.data));
            this.formatTreeSelectOptions(m.roleTreeOptions);
          }, err => {
          });
        });
      }
    });
  }

  // 格式化模态框树选择数据
  formatTreeSelectOptions(list: any) {
    list.forEach((item: any) => {
      item.title = item.name;
      item.key = item.id + '';
      delete item.name;
      delete item.id;
      item.isLeaf = !item.children?.length;
      if (item.children?.length) {
        this.formatTreeSelectOptions(item.children);
      }
    });
  }

  /**
   * 权限提交
   */
  submitPower() {
    const btnList: string[] = [];
    const menuList: string[] = [];
    this.moduleList.forEach((m: any) => {
      this.getCheckedRole(m.roleTreeOptions, menuList, btnList);
    });
    this.menuForm.pidList = btnList;
    this.menuForm.midList = menuList;
    this.setPermission();
  }

  getCheckedRole(list: any, menuList: string[], btnList: string[]) {
    list.forEach((item: any) => {
      if (item.checked === true) {
        if (item.type * 1 === 3) {
          btnList.push(item.key);
        } else {
          menuList.push(item.key);
        }
      }
      if (item.children?.length) {
        this.getCheckedRole(item.children, menuList, btnList);
      }
    });
  }

  /**
   * 角色详情
   */
  details(id: any) {
    this.roleService.details(id).subscribe((res: any) => {
      if (res.code !== 0) {
        this.createMessage('error', res.message);
        return;
      }
      const tabData = res.data;

      this.modalForm.get('id')!.setValue(tabData.id);
      this.modalForm.get('name')!.setValue(tabData.name);
      this.modalForm.get('keyword')!.setValue(tabData.keyword);
      this.modalForm.get('sort')!.setValue(tabData.sort);
      this.modalForm.get('rStats')!.setValue(tabData.rstats + '');
      this.modalForm.get('rRemarks')!.setValue(tabData.rremarks);
    }, err => {
    });
  }

  /**
   * 查询角色权限
   */
  queryPermission(id: any) {
    this.roleService.Permission({id}).subscribe((res: any) => {
      if (res.code !== 0) {
        this.createMessage('error', res.message);
        return;
      }
      const oldChecked: string[] = [];
      this.getBindRole(res.data, oldChecked);
      console.log('修改之前的权限', oldChecked);
      this.oldChecked = oldChecked;
    }, err => {
    });
  }

  getBindRole(list: any, result: string[] = []) {
    console.log(list);
    list.forEach((item: any) => {
      if (item.children?.length) {
        result.push(item.id + '');
        this.getBindRole(item.children, result);
      } else {
        result.push(item.id + '');
      }
    });
  }

  /**
   * 设置角色权限
   */
  setPermission() {
    this.roleService.setPermission(this.menuForm).subscribe((res: any) => {
      if (res.code !== 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '设置成功');
      this.handleCancel();
      this.list();
    }, err => {
    });
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning:警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

}
